package tool

// 路径处理的相关快速方法工具
import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
)

// PathExists 判断文件路径是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, PathError.WithDetails(path, err.Error())
}

// IsDir 判断文件夹是否存在
func IsDir(path string) (bool, error) {
	s, err := os.Stat(path)
	if err != nil {
		return false, PathError.WithDetails(path, err.Error())
	}
	return s.IsDir(), nil
}

// FormatFileSize 字节的单位转换 保留两位小数
//
func FormatFileSize(fileSize uint64) (size string) {
	if fileSize < 1024 {
		return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
	} else if fileSize < (1024 * 1024) {
		return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
	} else if fileSize < (1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
	} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
		return fmt.Sprintf("%.2fEB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
	}
}

// FormatCommunicationRate 通讯速率换算
// 传入参数单位为 B/s
func FormatCommunicationRate(fileSize float64) (size string) {
	if fileSize < 1024 {
		return fmt.Sprintf("%.2fB/s", fileSize/float64(1))
	} else if fileSize < (1024 * 1024) {
		return fmt.Sprintf("%.2fKB/s", fileSize/float64(1024))
	} else if fileSize < (1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fMB/s", fileSize/float64(1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fGB/s", fileSize/float64(1024*1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fTB/s", fileSize/float64(1024*1024*1024*1024))
	} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
		return fmt.Sprintf("%.2fEB/s", fileSize/float64(1024*1024*1024*1024*1024))
	}
}

// GetAllFile ...
func GetAllFile(pathname string) []string {
	rd, err := ioutil.ReadDir(pathname)
	if err != nil {
		return nil
	}
	ret := make([]string, 0, 16)
	for _, fi := range rd {
		if fi.IsDir() {
			ret = append(ret, GetAllFile(path.Join(pathname, fi.Name()))...)
		} else {
			ret = append(ret, path.Join(pathname, fi.Name()))
		}
	}
	return ret
}
